package 尚硅谷;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;

/**
 * @author zhangmin
 * @create 2022-03-23 21:26
 */
public class BlockingQueueDemo {
    public static void main(String[] args) throws InterruptedException {
        //List list=new ArrayList();
        BlockingQueue<String> blockingQueue=new ArrayBlockingQueue<>(3);
        //------------------------------------------------1、失败会直接报错-------------------------------------
        System.out.println(blockingQueue.add("a"));
        System.out.println(blockingQueue.add("b"));
        System.out.println(blockingQueue.add("c"));

        //System.out.println(blockingQueue.add("x"));---会报异常
        System.out.println(blockingQueue.remove());
        System.out.println(blockingQueue.remove());
        System.out.println(blockingQueue.remove());

        //System.out.println(blockingQueue.remove()); ---会报异常

        //------------------------------------------------2、失败不会报异常-------------------------------------
        System.out.println(blockingQueue.offer("a"));
        System.out.println(blockingQueue.offer("b"));
        System.out.println(blockingQueue.offer("c"));

        System.out.println(blockingQueue.offer("x"));//false:但是不报错

        System.out.println(blockingQueue.poll());
        System.out.println(blockingQueue.poll());
        System.out.println(blockingQueue.poll());

        System.out.println(blockingQueue.poll());//false:但是不报错


        //------------------------------------------------3、阻塞,一直等到成果才会继续-------------------------------------
        blockingQueue.put("a");
        blockingQueue.put("b");
        blockingQueue.put("c");
        System.out.println("======================");
        //blockingQueue.put("x");
        blockingQueue.take();
        blockingQueue.take();
        blockingQueue.take();
        blockingQueue.take();

        //------------------------------------------------4、当失败时，等待一定的时间-------------------------------------
        blockingQueue.offer("a", 2L,TimeUnit.SECONDS);
        blockingQueue.offer("a", 2L,TimeUnit.SECONDS);
        blockingQueue.offer("a", 2L,TimeUnit.SECONDS);
        blockingQueue.offer("a", 2L,TimeUnit.SECONDS);//这里会等待2s再执行

    }
}
